package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.common.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("sendMsg")
    public R<String> sendMsg(@RequestBody User user){
        String phone = user.getPhone();
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        //SMSUtils.sendMessage("传智健康","SMS_195226089",phone,code);
        log.info("code={}",code);
        //session.setAttribute("code",code);
        redisTemplate.opsForValue().set("code_"+phone,code,2, TimeUnit.MINUTES);
        return R.success("短信发送成功");
    }
    @PostMapping("login")
    public R<User> login(@RequestBody Map<String,String> map,HttpSession session){
        String phone = map.get("phone");
        String code1 = map.get("code");
        log.info(code1);
        //String code2 = session.getAttribute("code").toString();
        String code2 = (String) redisTemplate.opsForValue().get("code_" + phone);
        log.info(code2);
        if (!StringUtils.equals(code1,code2)){
            return R.error("验证码错误");
        }
        LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery(User.class).eq(User::getPhone,phone);
        User user = userService.getOne(wrapper);
        if (user==null){
            user = new User();
            user.setPhone(phone);
            user.setStatus(1);
            userService.save(user);
        }
        session.setAttribute("userId",user.getId());
        redisTemplate.delete("code_"+phone);
        return R.success(user);
    }
}
